<?php

namespace Aiweline\AiReviewForMagentoProduct\Lib;

use GuzzleHttp\Client;
use Aiweline\AiReviewForMagentoProduct\Lib\Magento\AdminToken;
use Aiweline\AiReviewForMagentoProduct\Lib\Magento\Config;

class Review
{
    static string $admin_token = '';
    static array $products = [];

    static function filePushToMagento(int $store_id, string $fileName, array $merge = [])
    {
        $file = __DIR__ . '/Review/' . $fileName;
        # 检测xlsx
        if (strpos($fileName, '.xlsx') === false) {
            return;
        }
        if (!file_exists($file)) {
            return;
        }
        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
        $reader->setReadDataOnly(true);
        $spreadsheet = $reader->load($file);
        $sheet = $spreadsheet->getActiveSheet();
        $rows = $sheet->toArray();
        $rows = array_slice($rows, 1);
        $data = [];
        foreach ($rows as $row) {
            if (!$row[0]) {
                continue;
            }
            $tmp = [
                'sku' => $row[0],
                'name' => $row[1],
                'title' => $row[2],
                'content' => $row[3],
                'score' => self::generateRandomScore(),
                'time' => $row[4],
                'store_id' => $store_id,
            ];
            $tmp = array_merge($tmp, $merge);
            $data[] = $tmp;
        }
        // 调用Magento API导入评论数据
        foreach ($data as $review) {
            self::importReviewToMagento($store_id, $review);
        }
    }

    // 定义生成随机评分的方法
    static function generateRandomScore()
    {
        $randomNumber = rand(1, 100);
        if ($randomNumber <= 10) {
            return 3;
        } elseif ($randomNumber <= 30) {
            return 4;
        } else {
            return 5;
        }
    }

    // 定义导入评论到Magento的函数
    static function importReviewToMagento(int $store_id, array $review)
    {
        // 接口文档
        $bearerToken = AdminToken::token();

        // 使用 Guzzle 发送请求
        $client = new Client();
        // 查询产品ID
        $productId = self::getProductIdBySku($review['sku']);
        if (!$productId) {
            // 处理产品未找到的情况
            echo "Product not found for SKU: " . $review['sku'];
            return;
        }
        # 10/22/2024 转换成 2024-10-22 00:00:00
        $review['time'] = date('Y-m-d H:i:s', strtotime($review['time']));
        // 使用查询到的产品ID来构建导入评论的API URL
        $apiUrl = Config::api('reviews');
        $response = $client->request('post', $apiUrl, [
            'json' => [
                'review' => [
                    'nickname' => $review['name'],
                    'title' => $review['title'] ?: 'Review for ' . $review['name'],
                    'detail' => $review['content'],
                    'ratings' => [
                        [
                            'rating_name' => 'Price',
                            'value' => self::generateRandomScore()
                        ],
                        [
                            'rating_name' => 'Value',
                            'value' => self::generateRandomScore()
                        ],
                        [
                            'rating_name' => 'Quality',
                            'value' => self::generateRandomScore()
                        ]
                    ],
                    "review_entity" => "product",
                    "review_status" => 1,
                    "entity_pk_value" => $productId, // 使用查询到的产品ID
                    'created_at' => $review['time'],
                    'stores' => [
                        $store_id
                    ]
                ]
            ],
            'headers' => [
                'Content-Type' => 'application/json',
                'accept' => 'application/json',
                'Authorization' => 'Bearer ' . $bearerToken
            ],
            'verify' => false // 去掉ssl验证
        ]);

        if ($response->getStatusCode() !== 200) {
            // 打印响应体 body 和响应头
            dd($response);
            return;
        }

        // 处理响应
        $responseData = json_decode($response->getBody()->getContents(), true);
        if (isset($responseData['message'])) {
            echo "Error: " . $responseData['message'];
        } else {
            echo "Review imported successfully: " . $responseData['id'] . "\n";
        }
    }

    // 新增: 获取产品ID的方法
    static function getProductIdBySku(string $sku): ?int
    {
        // 检查缓存中是否存在该SKU的产品ID
        if (isset(self::$products[$sku])) {
            return self::$products[$sku];
        }

        $apiUrl = Config::api('products/' . $sku);
        $bearerToken = AdminToken::token();

        // 使用 Guzzle 发送请求
        $client = new Client();
        $productResponse = $client->request('get', $apiUrl, [
            'headers' => [
                'Content-Type' => 'application/json',
                'accept' => 'application/json',
                'Authorization' => 'Bearer ' . $bearerToken
            ],
            'verify' => false // 去掉ssl验证
        ]);
        $productData = json_decode($productResponse->getBody()->getContents(), true);
        if (isset($productData['id'])) {
            $productId = $productData['id'];
            // 缓存产品ID十分钟
            self::$products[$sku] = $productId;
            return $productId;
        } else {
            // 处理产品未找到的情况
            echo "Product not found for SKU: " . $sku;
            return null;
        }
    }
}